#include "blux_v20.h"
#include "rtthread.h"
#include <rtdevice.h>

uint8_t    m_LUX_V20_BUF[8];                         	
uint16_t   m_LUX_V20_Data = 0;  

static struct rt_i2c_bus_device *blux_i2c_bus;

uint8_t B_LUX_V20_Multiple_read(void)
{ 

#if 0
  uint8_t vRval = 0;
  uint8_t i;	
  IIC_Start();
  IIC_Send_Byte(B_LUX_V20_SlaveAddress+1); 
  IIC_Wait_Ack();
  
  for (i=0; i<3; i++)
  {
    m_LUX_V20_BUF[i] = IIC_Read_Byte(0);
    if (i == 0x02)
    {
      IIC_NAck();
    }
    else
    {		
      IIC_Ack();
    }
  }
  
  IIC_Stop(); 
  return vRval;
#endif

    rt_i2c_master_recv(blux_i2c_bus, B_LUX_V20_SlaveAddress, RT_I2C_RD, &m_LUX_V20_BUF[0], 3);

}

uint8_t B_LUX_V20_Single_Write(uint8_t REG_Address)
{
    uint8_t single_val = REG_Address;
    rt_i2c_master_send(blux_i2c_bus, B_LUX_V20_SlaveAddress, RT_I2C_WR, &single_val, 1);
    return 0;
}

void blux_v20_Init(void) 
{
    blux_i2c_bus = (struct rt_i2c_bus_device *)rt_device_find("i2c2");
    if (blux_i2c_bus == RT_NULL)
    {
        rt_kprintf("cann't find i2c2\n");
        return;
    }
}


void B_LUX_V20_GetLux(uint32_t *vLux)
{  
  float temp = 0.0;
  B_LUX_V20_Single_Write(0x01);                     // power on
  B_LUX_V20_Single_Write(0x10);                     // H- resolution mode 
  
  //delay_ms(180);                         			 //delay 180
  rt_thread_mdelay(180);
  
  B_LUX_V20_Multiple_read();                        //
  
  B_LUX_V20_Single_Write(0x00);                     // power off
  
  m_LUX_V20_Data = m_LUX_V20_BUF[0];
  rt_kprintf("%02x,%02x,%02x\n",m_LUX_V20_BUF[0],m_LUX_V20_BUF[1],m_LUX_V20_BUF[2]);
  m_LUX_V20_Data = (m_LUX_V20_Data<<8) + m_LUX_V20_BUF[1];  
  
  temp=(float)m_LUX_V20_Data/1.2;
  *vLux = (uint32_t)(temp/0.4);								//对照UT383 矫正公式

}

